package com.vnp.cooking;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.sileria.android.view.HorzListView;
import com.viewpagerindicator.TitlePageIndicator;
import com.vnp.cooking.adapter.ListCachlamAdapter;
import com.vnp.cooking.adapter.ListCachlamSmallAdapter;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.upload.UploadFile;
import com.vnp.cooking.utils.Common;
import com.vnp.cooking.utils.DecodeUtils;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class DangCongThucActivity extends Activity implements OnClickListener, OnTouchListener{
	PreferenceHelper preferenceHelper;
	LinearLayout mainScroll;
	ImageButton btnBack;
	Button  btnThembuocnau;
	ImageButton btnThemAnhCT;
	ImageView imgCoverCongthuc;
	Button btnDangcongthuc;
	
	TextView titleDangCt, titleCacbuoc;
	Cursor cursor;
	
	// cac thanh phan con
	EditText txtTenCongthuc;
	TextView txtMotaCongthuc;
	TextView txtDacdiemCt;
	TextView txtNguyenlieu;
	
	// Layout
	View llDoidieuCt;
	private static final String SCREEN_LABEL = "Dang cong thuc screen";
	
	
	// object
	ObjCookpad objCookpad = new ObjCookpad();
	
	private static final String TEMP_COVER_CT_FILE = "anuongCV.jpg";
//	private static final int CHANGE_COVER = 1;
	private static final int PICK_PHOTO = 1;
	private static final int CAPTURE_PHOTO = 2;
	
	// thoat
	Dialog d, dArlert, dS;
	boolean isPosted = false;
	boolean isProcess = false;
	
	static boolean isPostedDacdiem = false;
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			saveAllCT();
		}
	};
	
	Runnable rC = new Runnable() {
		
		@Override
		public void run() {
			takeImage();
		}
	};
	
	Runnable rMain = new Runnable() {
		
		@Override
		public void run() {
			gotoMain();
		}
	};
	
	Runnable rDadang = new Runnable() {
		
		@Override
		public void run() {
			gotoDadang();
		}
	};
	
	ProgressDialog progressDialog;
	Handler mHandler = new Handler();
	
	ListCachlamSmallAdapter adapter;
	View llCacbuoc;
	HorzListView hz_buoclam;
	Button btnViewCacbuoc;
	
	ProgressBar progressUpload;
	
	Dialog dChoose;
	
	
	Uri mCapturedImageURI;
	String selectedPath;
	Uri selectedImageUri;

	String TEMP_TAKE_IMAGE = Common.SDCARD_IMAGE + "tmp_take_photo.jpg";
	String file_path;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dang_cong_thuc);
		preferenceHelper = new PreferenceHelper(this);
		mainScroll = (LinearLayout) findViewById(R.id.main_scroll);
		KeyboardHelper.setupUI(DangCongThucActivity.this, mainScroll);
		
		objCookpad = getIntent().getParcelableExtra("objCookpad");
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		titleDangCt = (TextView) findViewById(R.id.txt_dangct_title);
		titleCacbuoc = (TextView) findViewById(R.id.txt_cacbuoc);
		btnThemAnhCT = (ImageButton) findViewById(R.id.btn_them_anh_ct);
		imgCoverCongthuc = (ImageView) findViewById(R.id.img_ct);
		progressUpload = (ProgressBar) findViewById(R.id.progressUpload);
		
//		btnViewCacbuoc = (Button) findViewById(R.id.btn_view_cacbuoc);
		
		llCacbuoc = (View) findViewById(R.id.ll_cacbuoc);
		hz_buoclam = (HorzListView) findViewById(R.id.horz_list_cac_buoc);
		int i1 = Utils.getScreenHeigh(this) / 80;
	    int i2 = (int)(2.5F * i1);
	    int i3 = (int)(0.03F * i1);
	    hz_buoclam.setSpacing(i3);
		
		
		
		txtTenCongthuc = (EditText) findViewById(R.id.txt_tenmonan);
		txtMotaCongthuc = (TextView) findViewById(R.id.txt_doi_dieu_ct);
		txtDacdiemCt = (TextView) findViewById(R.id.txt_dac_diem_ct);
		txtNguyenlieu = (TextView) findViewById(R.id.txt_nguyenlieu_ct);
		btnThembuocnau = (Button) findViewById(R.id.btn_them_buoc_nau);
		btnDangcongthuc = (Button) findViewById(R.id.btn_dang_ct);
		
		initFont();
		// layout
		init();
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}
	
	private void initFont() {
		titleDangCt.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		btnDangcongthuc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		titleCacbuoc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		btnThembuocnau.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
//		txtTenCongthuc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this), Typeface.BOLD);
		txtMotaCongthuc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		txtDacdiemCt.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		txtNguyenlieu.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this));
		
	}
	public void init() {
		txtTenCongthuc.setText(objCookpad.getNameCookpad());
		txtMotaCongthuc.setOnTouchListener(this);
		txtDacdiemCt.setOnTouchListener(this);
		btnBack.setOnClickListener(this);
		btnThemAnhCT.setOnTouchListener(this);
		txtNguyenlieu.setText("Nguyên liệu "+"("+TaoMonAnNguyenLieuActivity.objNguyenlieus.size()+")");
		txtNguyenlieu.setOnTouchListener(this);
		btnThembuocnau.setOnTouchListener(this);
		btnDangcongthuc.setOnClickListener(this);
		llCacbuoc.setOnClickListener(this);
//		btnViewCacbuoc.setOnClickListener(this);
		
		txtTenCongthuc.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView arg0, int actionId, KeyEvent arg2) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					KeyboardHelper.hideSoftKeyboard(DangCongThucActivity.this);
					txtTenCongthuc.clearFocus();
				}
				return true;
			}
		});
	}
	

	@Override
	public void onBackPressed() {
		showDialogThoat();
	}
	
	@Override
	public void onResume() {
		super .onResume();
		
		
		if (CacBuocThucHienActivity.objSteps.size() == 0) {
			llCacbuoc.setVisibility(View.GONE);
		} else {
			Log.i("DATA", "nhay vao cac buoc thuc hien");
			llCacbuoc.setVisibility(View.VISIBLE);
			adapter = new ListCachlamSmallAdapter(DangCongThucActivity.this, CacBuocThucHienActivity.objSteps);
			hz_buoclam.setAdapter(adapter);
		}
		
		txtNguyenlieu.setText("Nguyên liệu "+"("+TaoMonAnNguyenLieuActivity.objNguyenlieus.size()+")");
		
		if (isPostedDacdiem == true){
			txtDacdiemCt.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this), Typeface.BOLD);
		} else {
			
			Log.i("DATA", "False----------");
			
			txtDacdiemCt.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this), Typeface.NORMAL);
		}
		if (preferenceHelper.getDescCT().matches("")){
			txtMotaCongthuc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this), Typeface.NORMAL);
		} else {
			txtMotaCongthuc.setTypeface(Utils.getTypefaceRegular(DangCongThucActivity.this), Typeface.BOLD);
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			 if (isProcess == false) {
				 if (isPosted) {
					 Thread th = new Thread(){

							@Override
							public void run() {
								xoaboCongthuc();
							}
							
						};
						th.start();
//						d.dismiss();
						closeActivity();
				 } else {
					 showDialogThoat();
				}
			 } else {
				
			}
			break;
			
		case R.id.btn_them_anh_ct:
			
			break;
			
		case R.id.ll_cacbuoc:
			gotoThembuocnau();
			break;
			
		case R.id.btn_view_cacbuoc:
			gotoThembuocnau();
			break;
		case R.id.btn_thoat:
			dChoose.dismiss();
			break;
			
		case R.id.txt_doi_dieu_ct:
			
			break;
		case R.id.txt_dac_diem_ct:
			
			break;
		case R.id.txt_nguyenlieu_ct:
			
			break;
		
		case R.id.btn_them_buoc_nau:
			
			break;
		case R.id.btn_choose_image:
			dChoose.dismiss();
			openGallery();
			break;
		case R.id.btn_capture_image:
			dChoose.dismiss();
			mHandler.postDelayed(rC, 200);
			break;
			
		case R.id.btn_thoat_dang_ct:
			Thread th = new Thread(){

				@Override
				public void run() {
					xoaboCongthuc();
				}
				
			};
			th.start();
			d.dismiss();
			mHandler.postDelayed(rThoat, 200);
//			closeActivity();
			break;
		case R.id.btn_luu_nhap:
			d.dismiss();
			// luu nhap se thuc hien o day
			break;
		case R.id.btn_dang_ct:
			if (!txtTenCongthuc.getText().toString().equals("")) {
				if(!preferenceHelper.getDescCT().equals("")) {
					
					if (isPostedDacdiem == true){
						if (TaoMonAnNguyenLieuActivity.objNguyenlieus.size()!=0) {
							mHandler.removeCallbacks(r);
							mHandler.postDelayed(r, 300);	
						} else {
							Toast.makeText(DangCongThucActivity.this, "Nguyên liệu công thức không được để trống.", Toast.LENGTH_SHORT).show();
						}
						
					} else {
						Toast.makeText(DangCongThucActivity.this, "Đặc điểm công thức không được để trống.", Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(DangCongThucActivity.this, "Đôi điều về công thức không được để trống.", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(DangCongThucActivity.this, "Tên công thức không được để trống.", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btn_tieptuc_bst:
			dS.dismiss();
			mHandler.postDelayed(rDadang, 200);
			break;
		default:
			break;
		}
	}
	
	void gotoMain() {
		Intent t = new Intent(DangCongThucActivity.this, MainActivity.class);
		preferenceHelper.setDescCT("");
		preferenceHelper.setRecipeId("");
		TaoMonAnNguyenLieuActivity.objNguyenlieus.clear();
		CacBuocThucHienActivity.objSteps.clear();
		finish();
		t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
		startActivity(t);
	}
	


	@SuppressWarnings("deprecation")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PICK_PHOTO:
				Uri u = (Uri) data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				cursor = getContentResolver().query(u, filePathColumn,
						null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				file_path = cursor.getString(columnIndex);

				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm = DecodeUtils.decode(DangCongThucActivity.this,
						Uri.parse(file_path), 800, 800);

				if (bm == null) {
					Toast.makeText(DangCongThucActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				imgCoverCongthuc.setScaleType(ScaleType.CENTER_CROP);
				imgCoverCongthuc.setImageBitmap(bm);

				// upload image
				uploadImage();
				try {
					if (cursor != null){
						cursor.close();	
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				cursor.requery();

				break;
			case CAPTURE_PHOTO:
				
				try{

				String[] projection = { MediaStore.Images.Media.DATA };
				cursor = managedQuery(mCapturedImageURI, projection,null, null, null);
				int column_index_data = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				file_path = cursor.getString(column_index_data);
				Log.i("DATA", "File upload :" + file_path);

				Bitmap bm1 = DecodeUtils.decode(DangCongThucActivity.this,
						Uri.parse(file_path), 800, 800);
				if (bm1 == null) {
					Toast.makeText(DangCongThucActivity.this,
							"Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
					return;
				}
				imgCoverCongthuc.setScaleType(ScaleType.CENTER_CROP);
				imgCoverCongthuc.setImageBitmap(bm1);

				uploadImage();
				} finally{
					cursor.close();
				}

				break;

			default:
				break;
			}
		} else {
			Toast.makeText(DangCongThucActivity.this, "Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	   public void startManagingCursor(Cursor c) {
	    // TODO Auto-generated method stub
	    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {

	    	super.startManagingCursor(c); 

	    	}
	    }
	
	void uploadImage() {
		progressUpload.setVisibility(View.VISIBLE);
		RequestParams params = new RequestParams();
		params.put("user_id", preferenceHelper.getID());
		params.put("recipe_id", preferenceHelper.getRecipeId());
		try {
			params.put("browse_file", new File(file_path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://anuong.net/api/recipe/imageRecipe", params,
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						progressUpload.setVisibility(View.GONE);
						Toast.makeText(DangCongThucActivity.this,
								"Request failed.", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							int status = re.getInt("status");
							progressUpload.setVisibility(View.GONE);
							switch (status) {
							case 200:
								JSONObject data = re.getJSONObject("data");
								Log.i("DATA", "Data return: " + data.toString());
								break;
							case 400:

								Toast.makeText(DangCongThucActivity.this,
										"Cập nhật ảnh thất bại (400)",
										Toast.LENGTH_SHORT).show();
								break;
							case 404:
								Toast.makeText(DangCongThucActivity.this,
										"Cập nhật ảnh thất bại (404).",
										Toast.LENGTH_SHORT).show();
								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				});
	}
	
	
	public void onChangeCover(int requestCode, int resultCode, Intent data) {
		Uri u = (Uri) data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		cursor = getContentResolver().query(u, filePathColumn, null, null, null);
		cursor.moveToFirst();
		int columnIndex        = cursor.getColumnIndex(filePathColumn[0]);
		final String file_path = cursor.getString(columnIndex);
		
		
		Log.i("DATA", "File upload :"+file_path);
		
		Bitmap bm = DecodeUtils.decode(DangCongThucActivity.this, Uri.parse(file_path), 300, 300);
		
		
		File f = new File(file_path);
		FileOutputStream fo;
		try {
			fo = new FileOutputStream(f);
			bm.compress(CompressFormat.JPEG, 90, fo);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}  
		
		if (bm == null) {
			Toast.makeText(DangCongThucActivity.this, "Bạn chưa chọn ảnh!", Toast.LENGTH_SHORT).show();
			return;
		}
		
		imgCoverCongthuc.setScaleType(ScaleType.CENTER_CROP);
		imgCoverCongthuc.setImageBitmap(bm);
				
		
		progressUpload.setVisibility(View.VISIBLE);
		
		RequestParams params = new RequestParams();
		params.put("user_id", preferenceHelper.getID());
		params.put("recipe_id", preferenceHelper.getRecipeId());
		try {
			params.put("browse_file", f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		AsyncHttpClient client = new AsyncHttpClient();
		client.post("http://anuong.net/api/recipe/imageRecipe", params, new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressUpload.setVisibility(View.GONE);
				Toast.makeText(DangCongThucActivity.this, "Cập nhật ảnh thất bại.", Toast.LENGTH_SHORT).show();
			}
			

			@Override
			public void onSuccess(JSONObject re) {
				try {
					progressUpload.setVisibility(View.GONE);
					int status = re.getInt("status");
					switch (status) {
					case 200:
						JSONObject data = re.getJSONObject("data");
						String coverMonAn = data.getString("url");
						Log.i("DATA", "Cover: "+coverMonAn);
						preferenceHelper.setCoverUrl(coverMonAn);
						Log.i("DATA", "THanh cong");
						break;
					case 400:
						Toast.makeText(DangCongThucActivity.this, "Cập nhật ảnh thất bại.", Toast.LENGTH_SHORT).show();
						Log.i("DATA", "Thieu truong");
						break;
					case 404:
						Toast.makeText(DangCongThucActivity.this, "Cập nhật ảnh thất bại.", Toast.LENGTH_SHORT).show();
						Log.i("DATA", "ID khong chuan");
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		try {
			if (cursor != null){
				cursor=null;	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	// den trang mo ta cong thuc
	public void gotoMotaCT() {
		Intent t = new Intent(DangCongThucActivity.this, TaoMonAnCamNghiActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	// dac diem mon an
	public void gotoDacdiemCT() {
		Intent t = new Intent(DangCongThucActivity.this, DacDiemMonAnActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	// public void gotoNguyenlieu
	public void gotoNguyenlieu() {
		Intent t = new Intent(DangCongThucActivity.this, TaoMonAnNguyenLieuActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	// public void gotoThemBuocnau
	public void gotoThembuocnau() {
		Intent t = new Intent(DangCongThucActivity.this, CacBuocThucHienActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	// den trang doi dieu ve cong thuc
	public void gotoDoidieuCt(){
		Intent t = new Intent(DangCongThucActivity.this, TaoMonAnCamNghiActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	// show dialog sau khi them thanh cong
		public void showDialogThoat() {
			d = new Dialog(this, R.style.DialogSlideAnimLeft);
			d.requestWindowFeature(Window.FEATURE_NO_TITLE);
			d.setContentView(R.layout.dialog_thoat_dang_ct);
			
			Button btnThoat = (Button) d.findViewById(R.id.btn_thoat_dang_ct);
			Button btnLuu = (Button) d.findViewById(R.id.btn_luu_nhap);
			d.show();
			d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			d.setCanceledOnTouchOutside(true);
			d.getWindow().setGravity(Gravity.CENTER);
			d.show();
			
			// setonclick
			btnThoat.setOnClickListener(this);
			btnLuu.setOnClickListener(this);
		}
		
		/** HTTP CLIENT */
		public void xoaboCongthuc(){
			HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					// TODO Auto-generated method stub
					super.onFailure(error);
				}

				@Override
				public void onSuccess(JSONObject re) {
					try {
						int status = re.getInt("status");
						if (status == 200) {
							Log.i("DATA", "XOA THANH CONG");
							preferenceHelper.setDescCT("");
							preferenceHelper.setRecipeId("");
							
							preferenceHelper.setIdThoigian(-1);
							preferenceHelper.setIdLoaibua(-1);
							preferenceHelper.setIdDacdiem(-1);
							preferenceHelper.setIdDokho(-1);
							preferenceHelper.setIdLoaimonan(-1);
							preferenceHelper.setIdPhuongphap(-1);
							preferenceHelper.setIdNguongoc(-1);

							isPostedDacdiem = false;
							TaoMonAnNguyenLieuActivity.objNguyenlieus.clear();
							CacBuocThucHienActivity.objSteps.clear();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			});
			httpClientHelper.deleteCongthuc(preferenceHelper.getID(), preferenceHelper.getRecipeId());
		}
		
		
		// xuli tao folder anh
		private Uri getTempUri() {
			return Uri.fromFile(getTempFile());
		}

		private File getTempFile() {
			if (isSDCARDMounted()) {
				File f = new File(Common.SDCARD_IMAGE, TEMP_COVER_CT_FILE);
				try {
					f.createNewFile();
				} catch (IOException e) { }
				return f;
			} else {
				return null;
			}
		}

		private boolean isSDCARDMounted() {
			String status = Environment.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED))
				return true;
			return false;
		}
		
		void closeActivity(){
			finish();
			BuocThucHienActivity.objSteps.clear();
			overridePendingTransition(R.anim.open_main, R.anim.close_next);
		}
		
		// save tat ca cac cong thuc
		void saveAllCT() {
			isProcess = true;
			progressDialog = ProgressDialog.show(DangCongThucActivity.this, "", "Đang đăng công thức...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					super.onFailure(error);
					isPosted = true;
					isProcess = false;
					progressDialog.dismiss();
					Toast.makeText(DangCongThucActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onSuccess(JSONObject re) {
					int status;
					isPosted = true;
					isProcess = false;
					progressDialog.dismiss();
					try {
						status = re.getInt("status");
						switch (status) {
						case 200:
							showDialogThemThanhcong();
							Toast.makeText(DangCongThucActivity.this, "Cập nhật thành công.", Toast.LENGTH_SHORT).show();
							break;

						case 400:
							Toast.makeText(DangCongThucActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
							break;
						case 404:
							Toast.makeText(DangCongThucActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
						isPosted = true;
						isProcess = false;
						Toast.makeText(DangCongThucActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
					}
				}
			});
			
			httpClientHelper.saveALLCT(preferenceHelper.getID(), preferenceHelper.getRecipeId(), objCookpad.getNameCookpad(), preferenceHelper.getDescCT());
		}
		
		// show dialog dang thuc hien 1 hanh dong noa do
		public void showDialogProcess() {
			dArlert = new Dialog(DangCongThucActivity.this,
					R.style.DialogSlideAnimLeft);
			dArlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dArlert.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dArlert
					.findViewById(R.id.str_canhbao_thoat);
			Button btnThoat = (Button) dArlert.findViewById(R.id.btn_thoat);
			Button btnKoThoat = (Button) dArlert.findViewById(R.id.btn_ko_thoat);

			btnThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
					mHandler.removeCallbacks(rThoat);
					mHandler.postDelayed(rThoat, 200);
				}
			});

			btnKoThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
				}
			});

			dArlert.setCanceledOnTouchOutside(true);
			dArlert.show();
			dArlert.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dArlert.getWindow().setGravity(Gravity.CENTER);
		}
		
		// dialog them thanh cong
		// show dialog sau khi them thanh cong
		public void showDialogThemThanhcong() {
			dS = new Dialog(this, R.style.DialogSlideAnimLeft);
			dS.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dS.setContentView(R.layout.dialog_dang_thanhcong);
			TextView str_them_thanh_cong = (TextView) dS.findViewById(R.id.str_them_thanh_cong);
			
			str_them_thanh_cong.setText("Bạn đã đăng thành công món "+txtTenCongthuc.getText().toString()+" .");
			Button btnDong = (Button) dS.findViewById(R.id.btn_tieptuc_bst);
			dS.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dS.getWindow().setGravity(Gravity.CENTER);
			dS.show();
			
			// setonclick
			btnDong.setOnClickListener(this);
		}


		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (v.getId()) {
			case R.id.btn_them_anh_ct:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					/*Intent t = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					t.setType("image/*");
					startActivityForResult(t, CHANGE_COVER);*/
					showDialogChonanh();
				}
				break;
			case R.id.btn_them_buoc_nau:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					gotoThembuocnau();
				}
				break;
			case R.id.txt_doi_dieu_ct:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					gotoDoidieuCt();
				}
				break;
			case R.id.txt_dac_diem_ct:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					gotoDacdiemCT();
				}
				break;
			case R.id.txt_nguyenlieu_ct:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					gotoNguyenlieu();
				}
				break;
			default:
				break;
			}
			return false;
		}
		
		public void showDialogChonanh() {
			dChoose = new Dialog(this, R.style.DialogSlideAnim);
			dChoose.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChoose.setContentView(R.layout.dialog_choose_photo);

			Button btnChonanh = (Button) dChoose
					.findViewById(R.id.btn_choose_image);
			Button btnChupanh = (Button) dChoose
					.findViewById(R.id.btn_capture_image);

			Button btnThoat = (Button) dChoose.findViewById(R.id.btn_thoat);
			dChoose.show();
			dChoose.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChoose.setCanceledOnTouchOutside(true);
			dChoose.getWindow().setGravity(Gravity.BOTTOM);
			dChoose.show();

			// setonclick
			btnChonanh.setOnClickListener(this);
			btnChupanh.setOnClickListener(this);
			btnThoat.setOnClickListener(this);
		}
		
		// chon anh
		public void openGallery() {
			File ff = new File(TEMP_TAKE_IMAGE);
			if (ff.exists())
				ff.delete();
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("image/*");
			startActivityForResult(photoPickerIntent, PICK_PHOTO);
		}

		// chup anh
		public void takeImage() {
			String fileName = "temp.jpg";
			ContentValues values = new ContentValues();
			values.put(MediaStore.Images.Media.TITLE, fileName);
			mCapturedImageURI = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
			startActivityForResult(intent, CAPTURE_PHOTO);
		}
		
		void gotoDadang(){
			Intent t = new Intent(DangCongThucActivity.this, CongthucDadangActivity.class);
			preferenceHelper.setDescCT("");
			preferenceHelper.setRecipeId("");
			TaoMonAnNguyenLieuActivity.objNguyenlieus.clear();
			CacBuocThucHienActivity.objSteps.clear();
			finish();
			t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			t.putExtra("userID", preferenceHelper.getID());
			startActivity(t);
		}
		
		
		
		
		
		
}	
